<template>
    <div ref="chartEl" class="chart-container"></div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, watch, onUnmounted } from 'vue'
  import * as echarts from 'echarts'
  
  // 定义props类型
  interface BarData {
    categories: string[]
    data: number[]
  }
  
  const props = defineProps<{
    chartData: BarData
  }>()
  
  const chartEl = ref<HTMLElement>()
  let chart: echarts.ECharts | null = null
  
  onMounted(() => {
    if (chartEl.value) {
      chart = echarts.init(chartEl.value)
      updateChart()
    }
  })
  
  // 监听窗口变化
  const handleResize = () => chart?.resize()
  window.addEventListener('resize', handleResize)
  onUnmounted(() => window.removeEventListener('resize', handleResize))
  
  watch(() => props.chartData, updateChart, { deep: true })
  
  function updateChart() {
    if (!chart) return
  
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: props.chartData.categories,
        axisLabel: {
          rotate: 45,
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} kWh'
        }
      },
      series: [
        {
          name: '能源消耗',
          type: 'bar',
          data: props.chartData.data,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#36a2eb' },
              { offset: 1, color: '#4bc0c0' }
            ]),
            borderRadius: [6, 6, 0, 0]
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.3)'
            }
          }
        }
      ],
      grid: {
        left: '3%',
        right: '3%',
        bottom: '10%',
        containLabel: true
      }
    }
  
    chart.setOption(option)
  }
  </script>
  
  <style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
    min-height: 300px;
  }
  </style>